﻿
<Cmdlet(VerbsCommon.Set, "SqlConnection")>
Public Class SetSqlConnection
    Inherits PSCmdlet

    <Parameter(ValueFromPipelineByPropertyName:=True)>
    Public Property Database As String
    <Parameter(ValueFromPipelineByPropertyName:=True)>
    Public Property CommandTimeout As Integer = -1
    <Parameter>
    Public Property ConnectionName As String = "Default"

    Protected Overrides Sub EndProcessing()
        MyBase.EndProcessing()

        If Not DBInfo.Connections.ContainsKey(Me.ConnectionName) Then
            WriteWarning(DBInfo.NoConnection(Me.ConnectionName))
            Exit Sub
        End If

        If Me.Database IsNot Nothing Then SetDatabase()
        If Me.CommandTimeout >= 0 Then SetCommandTime()
    End Sub

    Private Sub SetDatabase()
        Try
            DBInfo.Connections(Me.ConnectionName).Connection.ChangeDatabase(Database)
        Catch ex As Exception When TypeOf ex Is NotSupportedException OrElse TypeOf ex Is NotImplementedException
            WriteWarning(String.Format("Changing the database is not available for this provider: {0}", DBInfo.Connections(Me.ConnectionName).Type))
        End Try
    End Sub

    Private Sub SetCommandTime()
        DBInfo.Connections(Me.ConnectionName).CommandTimeout = Me.CommandTimeout
    End Sub


End Class
